const user = JSON.parse(sessionStorage.getItem("user"));
if (user) {
  $(".userslogin>span:nth-child(2)").html(user.username);
}
let pwd;
$(".pwdchange").hide();
$(".fix-a-time").hide();

const viewvip = function () {
  const vipimg = document.querySelectorAll("img");
  const username = document.querySelector(
    ".userslogin span:nth-child(2)"
  ).innerText;
  // console.log(username);
  const [car_id, car_place, balance, usertel, userpwd, booklotsnum, name] = [
    document.querySelectorAll("#car_id"),
    document.querySelectorAll("#car_place"),
    document.querySelectorAll("#balance"),
    document.querySelectorAll("#usertel"),
    document.querySelectorAll("#userpwd"),
    document.querySelectorAll("#booklotsnum"),
    document.querySelectorAll("#username"),
  ];
  request({
    method: "post",
    url: "/v1/query_vip",
    data: {
      username: username,
    },
    success: function (res) {
      console.log(res.data);
      pwd = res.data[2][0].password;
      vipimg.forEach(
        v => (v.src = `../../resources/image${res.data[2][0].userimage}`)
      );
      car_id.forEach(v => (v.innerHTML = res.data[0][0].carnum));
      car_place.forEach(v => (v.innerHTML = res.data[0][0].parklots));
      balance.forEach(v => (v.innerHTML = res.data[1][0].balance));
      usertel.forEach(v => (v.innerHTML = res.data[2][0].usertel));
      // userpwd.forEach(v => (v.innerHTML = res.data[2][0].password));
      booklotsnum.forEach(v => (v.innerHTML = res.data[2][0].booklotsnum));
      name.forEach(v => (v.innerHTML = res.data[2][0].username));
    },
  });
};
viewvip();

let vlist = document.querySelectorAll(".vipdetail .vipdetail-list a");
let vContent = document.querySelector(".vipdetail-content");
// console.log(vlist);
vlist.forEach(v => {
  v.onclick = function () {
    vlist.forEach(v => v.classList.remove("active"));
    v.classList.add("active");
    if (v.text == "车位查询") {
      vContent.innerHTML = `<div class="car-place">
      <h1>可用车位查询<i class="bi bi-arrow-down-right-square-fill"></i></h1>
      <form action="javascript:;" method="get">
          <input type="text" id="designated" placeholder="请输入指定车位号">
          <input type="submit" id="designated_btn" value="查询">
      </form>
      <div>
          <div class="place-btn">
              <button class="btn-active">A区</button>
              <button>B区</button>
              <button>C区</button>
          </div>
          <div class="place-tips">
              <span>空闲车位<i class="bi bi-circle-fill"></i></span>
              <span>占用车位<i class="bi bi-circle-fill"></i></span>
              <span>已预定<i class="bi bi-circle-fill"></i></span>
              <span>维护中<i class="bi bi-circle-fill"></i></span>
          </div>
      </div>
      <table></table>
    </div>`;
    } else if (v.text == "车位预定") {
      vContent.innerHTML = `<div id="predetermine">
      <div>
          <h2>可预定车位：<i class="bi bi-question-circle-fill" title="预定为 15 ￥/天"></i></h2>
          <div>
              <span>选择显示数量：</span>
              <select name="" id="viewnum">
                  <option value="10">10</option>
                  <option value="20" selected="selected">20</option>
                  <option value="30">30</option>
                  <option value="40">40</option>
              </select>
          </div>
          <div>
              <span>选择页数：</span>
              <select name="" id="viewpage"></select>
          </div>
          <button>查询</button>
      </div>
      <div class="pred-list"></div>
      <div class="limit"></div>
      </div>`;

      let nowPage;
      let pageCount;
      function getPdata(page, size) {
        request({
          url: `/v1/predetermine?nowPage=${page}&size=${size}`,
          success: function (res) {
            // console.log(res);
            nowPage = res.data.nowPage;
            pageCount = res.data.pageCount;

            $("#predetermine>.pred-list").html(
              res.data.data.map(v => {
                return `<div class="pred-item" title="点我">${v.id}</div>`;
              })
            );
            let vpage = "";
            for (let i = 1; i <= pageCount; i++) {
              vpage += `<option value="${i}">${i}</option>`;
            }
            $("#viewpage").html(vpage);
            //分页按钮
            let start = Math.max(1, nowPage - 2);
            let end = Math.min(start + 4, pageCount);
            start = Math.max(end - 4, 1);
            let btns = "";
            for (let j = start; j <= end; j++) {
              btns += `<button class="page ${
                nowPage == j ? "active" : ""
              }">${j}</button>`;
            }
            $("#predetermine>.limit").html(`
            <button class="pre ${nowPage == 1 ? "disa" : ""}">上一页</button>
            ${btns}
            <button class="next ${
              nowPage == pageCount ? "disa" : ""
            }">下一页</button>
            `);
          },
        });
      }
      getPdata(1, 20);

      $("#predetermine>div>button:contains(查询)").on("click", function () {
        getPdata($("#viewpage").val(), $("#viewnum").val());
      });
      $("#predetermine>.pred-list").on("click", ".pred-item", function () {
        $(".fix-a-time").fadeIn();
        $(".fix-a-time span").html($(this).text());
        $(".fix-a-time .pretime").on("click", "button", function () {
          $(this).addClass("active").siblings().removeClass("active");
        });
        $(".fix-a-time .pretime").on("focus", "input", function () {
          $(this).parent().children("button").removeClass("active");
        });
      });

      $(".fix-a-time>.YN").on("click", "button:contains(确定)", function () {
        if (
          $(".pretime>input").val() == "" &&
          $(".pretime>button.active").length == 0
        ) {
          Tip.setTip("请选择时间");
        } else {
          request({
            method: "post",
            url: "/v1/Prednum",
            data: {
              username: user.username,
            },
            success: function (res) {
              console.log(res);
              if (res.data.booklotsnum) {
                Tip.setTip("您已有一个预定信息");
              } else {
                let ctime;
                let price;
                if (!$(".pretime>input").val().trim()) {
                  ctime =
                    new Date().getTime() * 1 +
                    +$(".pretime>button.active").text() * 24 * 60 * 60 * 1000;
                  price = res.data.price * $(".pretime>button.active").text();
                } else {
                  ctime =
                    new Date().getTime() * 1 +
                    +$(".pretime>input").val() * 24 * 60 * 60 * 1000;
                  price = res.data.price * $(".pretime>input").val();
                }
                Tip.setTip(`需支付${price}元，是否预定?`, function () {
                  if (res.data.balance < price) {
                    Tip.setTip("余额不足，请充值。");
                  } else {
                    request({
                      method: "put",
                      url: "/v1/alterPred",
                      data: {
                        arrive_time: ctime,
                        id: $(".fix-a-time span").text(),
                        username: user.username,
                        balance: res.data.balance - price,
                      },
                      success: function (res) {
                        if (res.code == 200) {
                          Tip.setTip("预定成功！", function () {
                            location.reload();
                          });
                        }
                      },
                    });
                  }
                });
              }
            },
          });
        }
      });
      $(".fix-a-time>.YN").on("click", "button:contains(取消)", function () {
        $(".fix-a-time").hide();
        $(".fix-a-time .pretime>button").removeClass("active");
        $(".fix-a-time .pretime>input").val("");
      });

      //分页按钮
      $("#predetermine>.limit").on("click", "button.page", function () {
        $(this).addClass("active").siblings().removeClass("active");
        getPdata($(this).text(), $("#viewnum").val());
      });
      $("#predetermine>.limit").on("click", "button.pre", function () {
        getPdata(nowPage - 1, $("#viewnum").val());
      });
      $("#predetermine>.limit").on("click", "button.next", function () {
        getPdata(nowPage - -1, $("#viewnum").val());
      });
    } else if (v.text == "停车缴费") {
      vContent.innerHTML = "停车缴费";
    } else if (v.text == "停车信息") {
      vContent.innerHTML = "停车信息";
    } else if (v.text == "帐号信息") {
      vContent.innerHTML = `<table class="vtable">
      <tr>
          <td class="avatar">
            <span>头像: </span>
            <i class="camera bi bi-camera-fill"></i>
            <img src="../../resources/image/userimg/1.jpeg" alt="">
          </td>
          <td><span>车牌号: </span><span id="car_id">鄂xxx</span></td>
      </tr>
      <tr>
          <td><span>用户名: </span><span id="username">wei</span></td>
          <td><span>密码: </span><span id="userpwd" style="font-size: 3rem;">·····</span><i class="bi bi-eye-fill"></i><i class="bi bi-eye-slash-fill"></i></td>
      </tr>
      <tr>
          <td><span>已预订车位: </span><span id="booklotsnum">xxx</span></td>
          <td><span>余额：</span><span id="balance">xxx</span></td>
      </tr>
      <tr>
          <td><span>手机号: </span><span id="usertel">xxx</span></td>
          <td></td>
      </tr>
      <tr>
          <td style="width: 800px; justify-content: space-around;">
              <button id="changepwd">修改密码</button><button>余额充值</button><button>退出登录</button>
          </td>
      </tr>
  </table>`;

      viewvip();

      //头像上传
      $(".vtable .avatar img").on("mouseenter", function () {
        $(this).prev().show();
      });
      $(".vtable .avatar i").on("mouseleave", function () {
        $(this).fadeOut();
      });

      //密码显示与否
      $("#userpwd~i")
        .css({
          position: "absolute",
          right: "100px",
          cursor: "pointer",
        })
        .eq(0)
        .hide();
      $("#userpwd~i").on("click", function () {
        $(this).hide().siblings().show();
        if ($(this).index() == 3) {
          $("#userpwd").html(pwd).css({ fontSize: "1.2rem" });
        } else {
          $("#userpwd").html(`·····`).css({ fontSize: "3rem" });
        }
      });

      //修改密码按钮
      $("table #changepwd").on("click", function () {
        $(".pwdchange").fadeIn("slow");
      });
      $(".pwdchange>div>button").on("click", function () {
        const v1 = $("#newpwd").val().trim();
        const v2 = $("#renewpwd").val().trim();
        if (!$(this).index()) {
          if (v1 == "" || v2 == "") {
            Tip.setTip("新密码不能为空!");
          } else if (v1 != v2) {
            Tip.setTip("两次输入密码不一致!");
          } else if (!/^.{6,15}$/.test(v1)) {
            Tip.setTip("密码长度6到15位!");
          } else {
            request({
              method: "put",
              url: "/v1/changepwd",
              data: {
                userpwd: v1,
                username: user.username,
              },
              success: function (res) {
                console.log(res);
                if (res.code == 200) {
                  Tip.setTip("密码修改成功!请重新登录..", function () {
                    $("#newpwd").val("");
                    $("#renewpwd").val("");
                    sessionStorage.removeItem("user");
                    location.replace("../login/login.html");
                  });
                } else {
                  Tip.setTip("密码修改失败..", function () {
                    $("#newpwd").val("");
                    $("#renewpwd").val("");
                  });
                }
              },
            });
          }
        } else {
          $("#newpwd").val("");
          $("#renewpwd").val("");
          $(".pwdchange").hide();
        }
      });

      //退出登录按钮
      $("#changepwd")
        .siblings()
        .eq(1)
        .on("click", function () {
          $(".userslogin>a:nth-child(3)").trigger("click");
        });
    }
  };
});

$(".userslogin>a:nth-child(3)").on("click", function () {
  Tip.setTip("确定退出？", function () {
    sessionStorage.removeItem("user");
    location.replace("../../index.html");
  });
  $("#tipShadow").on("click", function () {
    $(this).remove();
    $("#theTip").remove();
  });
});
